package cn.com.lms.business.exam.web;

import cn.com.lms.business.core.constant.ErrorEnum;

import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.exam.persistence.entity.QuestionCategory;
import cn.com.lms.business.exam.service.QuestionCategoryService;
import cn.com.lms.business.exam.web.vo.TreeNode;
import cn.com.lms.business.log.enums.ActionTypeEnum;
import cn.com.lms.business.log.persistence.entity.UserActionLog;
import cn.com.lms.business.log.service.UserActionLogService;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import com.bnzj.cloud.business.core.persistence.entity.SysUser;

import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.rest.ResponseResult;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author zhangzhenjiang
 * @createDate 2020/3/14
 * @description
 */
@Tag(name = "题库分类", description = "题库的分类管理")
@RestController
@RequestMapping("/exam/question/category")
public class QuestionCategoryController {

    @Autowired
    QuestionCategoryService questionCategoryService;

    @Autowired
    UserActionLogService userActionLogService;


    @Operation(summary = "保存")
    @PostMapping("/save")
    public ResponseResult<?> addQuestionCategory(@RequestBody QuestionCategory questionCategory) {
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();

        QuestionCategory queryCatetoryName=new QuestionCategory();
        queryCatetoryName.setCategoryName(questionCategory.getCategoryName());
        queryCatetoryName.setParentId(questionCategory.getParentId());
       long count= questionCategoryService.findAll(queryCatetoryName).stream().filter(m->m.getIsDelete().equals(false) && m.getCategoryName().equals(questionCategory.getCategoryName())).count();
        if(count>0){
            throw new BusinessException(ErrorEnum.CATEGORY_NAME_EXIST.getMessage(), "" + ErrorEnum.CATEGORY_NAME_EXIST.getCode());
        }

        questionCategory.setCreator(String.valueOf(sysUser.getId()) );
        questionCategory.setCreateTime(new Date());
        questionCategory.setCreatorName(sysUser.getCname());
        questionCategory.setIsDelete(false);
        QuestionCategory result = questionCategoryService.save(questionCategory);
        if (result != null && sysUser != null) {
            UserActionLog userActionLog = new UserActionLog(sysUser.getCname(), sysUser.getCname() + ActionTypeEnum.ADD.getName() + "id 为" + result.getId() + "的题库分类", ActionTypeEnum.ADD.getValue(), "成功");
            userActionLogService.save(userActionLog);
        }

        return ResponseResult.success();
    }


    @Operation(summary = "更新")
    @PostMapping("/update")
    public ResponseResult<?> updateQuestionCategory(@RequestBody QuestionCategory questionCategory) {
        if (ObjectUtils.isEmpty(questionCategory.getId())) {
            throw new BusinessException(ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getMessage(), "" + ErrorEnum.PARAMETER_CANNOT_BE_EMPTY.getCode());
        }

        QuestionCategory queryCatetoryName=new QuestionCategory();
        queryCatetoryName.setCategoryName(questionCategory.getCategoryName());
        queryCatetoryName.setParentId(questionCategory.getParentId());
        long count= questionCategoryService.findAll(queryCatetoryName).stream().filter(m->m.getIsDelete().equals(false) && m.getCategoryName().equals(questionCategory.getCategoryName()) && m.getId()!=questionCategory.getId()).count();
        if(count>0){
            throw new BusinessException(ErrorEnum.CATEGORY_NAME_EXIST.getMessage(), "" + ErrorEnum.CATEGORY_NAME_EXIST.getCode());
        }

        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        questionCategory.setModifyTime(new Date());
        questionCategory.setCreator(String.valueOf(sysUser.getId()));
        questionCategory.setCreatorName(sysUser.getCname());

        QuestionCategory result = questionCategoryService.updateQuestionCategory(questionCategory);
        // 用户操作日志
        if (result != null && sysUser != null) {
            UserActionLog userActionLog = new UserActionLog(sysUser.getCname(), sysUser.getCname() + ActionTypeEnum.EDIT.getName() + "id 为" + result.getId() + "的题库分类", ActionTypeEnum.EDIT.getValue(), "成功");
            userActionLogService.save(userActionLog);
        }
        return ResponseResult.success(result);
    }

    @Operation(summary = "根据id查询")
    @GetMapping("/one/{id}")
    public ResponseResult<QuestionCategory> getById(@Parameter(name = "id", description = "主键", required = true) @PathVariable("id") Long id) {
        Optional<QuestionCategory> paperOpt = questionCategoryService.findById(id);
        if (!paperOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();

        // 用户操作日志
        if (paperOpt.get() != null && sysUser != null) {
            UserActionLog userActionLog = new UserActionLog(sysUser.getCname(), sysUser.getCname() + ActionTypeEnum.SELECT.getName() + "id 为" + paperOpt.get().getId() + "的题库分类", ActionTypeEnum.SELECT.getValue(), "成功");
            userActionLogService.save(userActionLog);
        }
        return ResponseResult.success(paperOpt.get());
    }

    @Operation(summary = "删除", description = "根据分类id删除分类及子类")
    @GetMapping("/delete/{id}")
    public ResponseResult<Integer> deleteById(@Parameter(name = "id", description = "主键", required = true) @PathVariable("id") Long id) {

        List<Long> childrenIds = questionCategoryService.findChildrenIds(id);
        if(childrenIds.size()>0){
            throw new BusinessException(ErrorEnum.CATEGORY_CHILD_EXIST.getMessage(), "" + ErrorEnum.CATEGORY_CHILD_EXIST.getCode());
        }

        childrenIds.add(id);
        Long total = questionCategoryService.findTotalQuestionByIds(childrenIds);
        if (total > 0) {
            throw new BusinessException(ErrorEnum.QUESTION_EXIST.getMessage(), "" + ErrorEnum.QUESTION_EXIST.getCode());

        }
        Integer count = questionCategoryService.updateIsDelete(true, childrenIds);

        // 用户操作日志
        SysUserVo sysUser = SystemUserUtil.getCurrentUser();
        if (count > 0 && sysUser != null) {
            UserActionLog userActionLog = new UserActionLog(sysUser.getCname(), sysUser.getCname() + ActionTypeEnum.DELETE.getName() + "id 为" + id + "的题库分类", ActionTypeEnum.SELECT.getValue(), "成功");
            userActionLogService.save(userActionLog);
        }
        return ResponseResult.success(count);

    }

    @Operation(summary = "分类树结构")
    @GetMapping("/getTree")
    public ResponseResult<?> getTree() {
        QuestionCategory root=QuestionCategory.getRoot();
        List<QuestionCategory> list = questionCategoryService.getMenuTree();
        root.setChildren(list);
        List<QuestionCategory> rootList=Arrays.asList(root);
        return ResponseResult.success(rootList);
    }

    @Operation(summary = "下拉分类树结构")
    @GetMapping("/getSelectTreeNode/{parentId}")
    public ResponseResult<?> getSelectTreeNode(@Parameter(name = "parentId", description = "主键", required = true) @PathVariable("parentId") Long parentId) {
        List<QuestionCategory> list = questionCategoryService.findAll();
        list = list.stream().filter(m -> m.getIsDelete() == false).collect(Collectors.toList());
        List<TreeNode> treeNodeList = new CopyOnWriteArrayList<>();
        List<QuestionCategory> categoryList = new CopyOnWriteArrayList<>();
        categoryList.addAll(list);
        list.stream().forEach(questionCategory -> {

            if(parentId.equals(questionCategory.getParentId())) {
                TreeNode treeNode = new TreeNode();
                treeNode.setId(questionCategory.getId());
                treeNode.setTitle(questionCategory.getCategoryName());
                treeNode.setPId(questionCategory.getParentId());
                treeNode.setValue(questionCategory.getId().toString());
                Long count = categoryList.stream().filter(m -> m.getParentId().equals(questionCategory.getId())).count();
                treeNode.setIsLeaf(count==0?true:false);
                treeNodeList.add(treeNode);
            }

        });

        return ResponseResult.success(treeNodeList);
    }

}

